<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of BOnlineAppointment
 *
 * @author I062261
 */
class BWeSport extends BApp {

    protected $eventTypeList = array();
    protected $messageListViewByEventType = array();

    public function getEventList($eventContext = NULL, $data = NULL) {
        //if no argument, return first level of eventTypes
        $list = array();
        if ($eventContext == NULL) {
            $context = new BWEvent();
            $context->spaceId = Blyn::app()->getActiveSpace()->getId();
            $context->appId = Blyn::app()->getActiveApp()->getId();
            $list = BWEvent::findAll($context);
        }

        return $list;
    }

    public function run($data = NULL) {
        parent::run($data);

        $eventType = new BWEventGroup();
        $count = $eventType->getRepository()->getCount();

        //init event types for app
        if ($count < 2) {
            $root = BWEventGroup::getRoot();
            $root->addChild('type.booking.court');
        }

        //init messageList view 
        $eventTypeList = $this->getEventTypeList('fullName');

        foreach ($eventTypeList as $id => $name) {
            if ($name == 'booking.court') {
                $this->messageListViewByEventType[$id] = 'bookingCourt_messageList';
            }
        }

        //Test bsheet
        /*
          $mapTable = new BSheet('testTable',  Blyn::app());
          $mapTable->addList(array('col1' => 'value1', 'col2' => 'value2'));
          $list = $mapTable->getList(array('itemData' => array('col1' => 'value1')));
          $item = $list->getItem('col1');
          $value = $item->getValue();

         */
    }

    public function runFollowBooking($operation = NULL, $data = NULL) {

        $updateControl = Blyn::app()->getUIManager()->getUpdateControl();
        $senderControl = Blyn::app()->getUIManager()->getSenderControl();
        $currentScreen = Blyn::app()->getUIManager()->getCurrentScreen();
        $wxMenu = new BUIWXMenu(Blyn::app()->getActiveOperation());
        $followBookingPage = new BUIWXControl('BUIWXControl_1');
        $currentScreen->addChildControl($followBookingPage);

        //test btreetable getValueList
        //example code for get booking date list with count
        /*
          $treeTable = new BTreeTable('BWInputValue');
          $itemData = array('city'=>'china.chongqing');
          $valueList = $treeTable->getValueList('startDate', array('itemData'=>$itemData));

          foreach ($valueList as $date=>$count) {
          $itemData['startDate'] = $date;
          $startTimeList = $treeTable->getValueList('startTime',array('itemData'=>$itemData));
          }
         * 
         */


        $availableList = null;
        if ($currentScreen->isAjaxLinkClicked('searchByVender')) {
            $model = new BDynamicFormModel();
            $model->addField('findText');
            if ($_POST != NULL && isset($_POST['BDynamicFormModel'])) {
                $model->attributes = $_POST['BDynamicFormModel'];
            }
            $findText = $model->findText;
            $availableList = $this->findInputValueListByVender($findText);
        }

//        if ($wxMenu->isMenuClicked('bookingCourt')) {
//            echo "bookingCourtbookingCourt";
//            $followBookingPage->addRenderView('booking_find_1', 'booking_find_1', array('controlPanel' => 'search'));
//        }
        $wxControl = new BUIWXControl('bookingCourt');
        if ($wxControl->isLinkClicked('bookingCourt')) {
            $screen = Blyn::app()->getUIManager()->getCurrentScreen();
            $wxControl = new BUIWXControl('page');
            $screen->addChildControl($wxControl);
            $wxControl->addRenderView('booking_find_1', 'booking_find_1', array('controlPanel' => 'search'));
        }

        if ($senderControl->isLinkClicked('booking_find_1')) {
            $nowCity = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('nowCity');
            $findType = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('findType');
            $data = array();
            if ($nowCity != null) {
                $data['nowCity'] = $nowCity;
            }
            if ($findType != null) {
                $findContext = array(
                    'findType' => $findType
                );
                $data['findContext'] = $findContext;
            }
            $followBookingPage->addRenderView('booking_find_1', 'booking_find_1', $data);
        }


//        if ($senderControl->isLinkClicked('booking_list')) {
//            $followBookingPage->addRenderView('booking_list', 'booking_list');
//        }
//        if ($senderControl->isLinkClicked('booking_list_available')) {
//            $followBookingPage->addRenderView('booking_list_available', 'booking_list_available');
//        }

        if ($senderControl->isLinkClicked('booking_list_unpaid_1')) {
            $followBookingPage->addRenderView('booking_list_unpaid_1', 'booking_list_unpaid_1');
        }

        if ($senderControl->isLinkClicked('booking_change_city')) {
            $followBookingPage->addRenderView('booking_change_city', 'booking_change_city');
        }

        if ($senderControl->isLinkClicked('booking_list')) {
            $flagText = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('flagText');
            $listPage = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('listPage');
            $findText = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('findText');
            $findContext = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('findContext');
            $nowCity = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('nowCity');
            $data = array();
            if ($flagText != NULL) {
                $data['flagText'] = $flagText;
            }
            if ($findText != NULL) {
                $data['findText'] = $findText;
            }
            if ($findContext != NULL) {
                $data['findContext'] = $findContext;
            }
            if ($nowCity != NULL) {
                $data['nowCity'] = $nowCity;
            }

            $followBookingPage->addRenderView('booking_list', $listPage, $data);
        }

        if ($senderControl->isLinkClicked('showBookingList_1')) {
            $flagText = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('flagText');
            //$eventId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('eventId');
            $findText = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('findText');
            $findContext = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('findContext');
            $nowCity = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('nowCity');
            $data = array();
            if ($flagText != NULL) {
                $data['flagText'] = $flagText;
            }
            if ($findText != NULL) {
                $data['findText'] = $findText;
            }
            if ($findContext != NULL) {
                $data['findContext'] = $findContext;
            }
            if ($nowCity != NULL) {
                $data['nowCity'] = $nowCity;
            }

            $followBookingPage->addRenderView('booking_list_1', 'booking_list_1', $data);
        }
        if ($senderControl->isLinkClicked('showSelectedPageBookingList_1_1')) {
            $flagText = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('flagText');
            $rowsPerPage = 50;
            $curPageNo = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('curPageNo');
            $findText = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('findText');
            $findContext = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('findContext');
            if (!isset($findContext) || !is_array($findContext))
                $findContext = array();
            if (isset($findText))
                $findContext['findText'] = $findText;

            $newContext = array();
            if (isset($findContext)) {
                if (is_array($findContext)) {
                    $findContext['limitStart'] = ($curPageNo - 1) * $rowsPerPage;
                }
                $newContext = $findContext;
            }
            $availableList = $this->findByFindText($findText, $newContext);
            $followBookingPage->addRenderView('booking_list_1', 'booking_list_1', array('availableList' => $availableList, 'findText' => $findText,
                'findContext' => $newContext, 'curPageNo' => $curPageNo, 'flagText' => $flagText));
        }

        if ($senderControl->isLinkClicked('search')) {
            $findText = '';
            $findType = '';
            $findContext = null;
            if (isset($_POST['BDynamicFormModel']['findText'])) {
                $findText = $_POST['BDynamicFormModel']['findText'];
            } else {
                $findText = '';
            }
            if (isset($_POST['BDynamicFormModel']['findType'])) {
                $findType = $_POST['BDynamicFormModel']['findType'];
            }
            $data = array();
            if ($findText != NULL) {
                $data['findText'] = $findText;
            }
            if ($findType != NULL) {
                $findContext = serialize(array('findType' => $findType));
                $data['findContext'] = $findContext;
            }
            $data['flagText'] = '"' . $findText . '"搜索结果';
            $data['backUrl'] = $followBookingPage->getLinkUrl(array('name' => 'searchNew', 'id' => 'searchPage'));

            $followBookingPage->addRenderView('booking_list_1', 'booking_list_1', $data);
        }
        if ($senderControl->isLinkClicked('searchPage')) {

            $followBookingPage->addRenderView('booking_search', 'booking_search');
        }

        if ($senderControl->isLinkClicked('showAddBooking_1')) {
            //$eventId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('eventId');
            $bookingId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('bookingId');
            $findText = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('findText');
            $findContext = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('findContext');
            $flagText = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('flagText');
            $followBookingPage->addRenderView('booking_add_1', 'booking_add_1', array(
                'bookingId' => $bookingId,
                'findText' => $findText,
                'findContext' => $findContext,
                'flagText' => $flagText
            ));
            //$updateControl->render();
            //Blyn::app()->end();
        }

        if ($senderControl->isLinkClicked('addToBookingCart_1')) {
            $bookingId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('bookingId');
            $findText = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('findText');
            $flagText = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('flagText');
            $findContext = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('findContext');
            $bookingItem = new BWInputValue($bookingId);
            $bookingList = new BTreeList($bookingItem);
            //default unit
            $unit = 'yuan';
            //default quantity
            $quantity = 1;
            $priceItem = $bookingList->getItem('price');
            if ($priceItem instanceof BTreeItem) {
                $price = $priceItem->value;
            }
            $userShoppingCart = new BWCart();
            $userShoppingCart->addList(array(
                'paymentStatus' => BCart::Payment_Status_Not_Paid,
                'productName' => $bookingList->getName(),
                'productId' => $bookingId,
                'price' => $price,
                'quantity' => $quantity,
                'addToBookingCartTime' => time(),
                'moneyUnit' => $unit));

            //change booking status
            $bookingList->addItem('addToBookingCartTime', time());
            $data = array();
            if ($findText != NULL) {
                $data['findText'] = $findText;
                $data['flagText'] = $flagText;
            }
            if ($findContext != NULL) {
                $data['findContext'] = $findContext;
                $data['flagText'] = $flagText;
            }

            $followBookingPage->addRenderView('booking_list_1', 'booking_list_1', $data);
            // $followBookingPage->addRenderView('toggleButton', 'booking_add_toggleButton', array('bookingStatus' => 'booking', 'bookingId' => $bookingId));
            //$followBookingPage->addRenderView('booking_list_unpaid_1', 'booking_list_unpaid_1', array('findText' => $findText, 'findContext' => $findContext));
        }

        if ($senderControl->isLinkClicked('showPayBooking_1')) {
            $followBookingPage->addRenderView('payBookingList_1', 'booking_list_unpaid_1');
        }

        //delete the bookingList
        if ($senderControl->isLinkClicked('deleteBookable_1')) {
            $cartId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('cartId');
            $cartTable = new BWCart();
            $bookingTable = new BTreeTable('BWInputValue');
            if (is_numeric($cartId) && $cartId > 0) {
                $cartList = $cartTable->getListById($cartId);
                $cartList->addItem('paymentStatus', bcart::Payment_Status_Paid_Cancelled);
                $bookingId = $cartList->getItem('productId')->value;
                $bookingList = $bookingTable->getListById($bookingId);
                $bookingList->addItem('addToBookingCartTime', 0);
            } else {
                if (!empty($_POST)) {
                    $checkedArray = $_POST['checkbox'];
                    foreach ($checkedArray as $cartId) {
                        if ($cartId != NULL) {
                            $cartList = $cartTable->getListById($cartId);
                            $cartList->addItem('paymentStatus', bcart::Payment_Status_Paid_Cancelled);
                            $bookingId = $cartList->getItem('productId')->value;
                            $bookingList = $bookingTable->getListById($bookingId);
                            $bookingList->addItem('addToBookingCartTime', 0);
                        }
                    }
                }
            }
            $followBookingPage->addRenderView('booking_list_unpaid_1');
        }


        if ($senderControl->isLinkClicked('payNow_1')) {
            $paidMoney = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('paidMoney');
            $paidCount = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('paidCount');
            $transactionTable = new BWTransaction();

            $transaction = $transactionTable->addList(array(
                'payerId' => Blyn::app()->getCurrentUser()->getId(),
                'paidTime' => time(),
                'cartItemNumber' => $paidCount,
                'paidMoney' => $paidMoney
            ));
            $transactionId = $transaction->getId();

            $bookingCart = new BWCart();
            $view = $bookingCart->getView(array('itemData' => array('paymentStatus' => bcart::Payment_Status_Not_Paid)));
            foreach ($view as $cartList) {
                if ($cartList instanceof BTreeList) {
                    $cartList->addItem('paymentStatus', BCart::Payment_Status_Paid);
                    $cartList->addItem('payerId', Blyn::app()->getCurrentUser()->getId());
                    $cartList->addItem('paidTime', time());
                    $cartList->addItem('transactionId', $transactionId);
                    //below update status for booking value
                    $bookingValueId = $cartList->getItem('productId')->getValue();
                    $bookingValueItem = new BWInputValue($bookingValueId);
                    $bookingList = new BTreeList($bookingValueItem);
                    $bookingList->addItem('bookingStatus', 'paid');
                    $bookingList->addItem('payerId', Blyn::app()->getCurrentUser()->getId());
                    $bookingList->addItem('paidTime', time());
                    $bookingList->addItem('transactionId', $transactionId);
                }
            }
            $followBookingPage->addRenderView('payBooking_1', 'booking_pay_view_1', array(
                'transactionId' => $transactionId,
                'paidMoney' => $paidMoney,
                'paidCount' => $paidCount));
            //$updateControl->render();
            //Blyn::app()->end();
        }
        if ($senderControl->isLinkClicked('payNow_2')) {
            $cartId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('cartId');
            $paidMoney = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('paidMoney');
            $paidCount = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('paidCount');
            $transactionTable = new BWTransaction();
            $transaction = $transactionTable->addList(array(
                'payerId' => Blyn::app()->getCurrentUser()->getId(),
                'paidTime' => time(),
                'cartItemNumber' => $paidCount,
                'paidMoney' => $paidMoney
            ));
            $transactionId = $transaction->getId();

            $bookingCart = new BWCart();
//            $view = $bookingCart->getView(array('itemData' => array('paymentStatus' => bcart::Payment_Status_Not_Paid)));
//            foreach ($view as $cartList) {
            if (is_numeric($cartId) && $cartId > 0) {
                $cartList = $bookingCart->getListById($cartId);
                $cartList->addItem('paymentStatus', BCart::Payment_Status_Paid);
                $cartList->addItem('payerId', Blyn::app()->getCurrentUser()->getId());
                $cartList->addItem('paidTime', time());
                $cartList->addItem('transactionId', $transactionId);
                //below update status for booking value
                $bookingValueId = $cartList->getItem('productId')->getValue();
                $bookingValueItem = new BWInputValue($bookingValueId);
                $bookingList = new BTreeList($bookingValueItem);
                $bookingList->addItem('bookingStatus', 'paid');
                $bookingList->addItem('payerId', Blyn::app()->getCurrentUser()->getId());
                $bookingList->addItem('paidTime', time());
                $bookingList->addItem('transactionId', $transactionId);
            }
//            }
            $followBookingPage->addRenderView('payBooking_1', 'booking_pay_view_1', array(
                'transactionId' => $transactionId,
                'paidMoney' => $paidMoney,
                'paidCount' => $paidCount));
            //$updateControl->render();
            //Blyn::app()->end();
        }
        if ($senderControl->isLinkClicked('showMyBookingList_1')) {
            $paymentStatus = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('paymentStatus');
            if ($paymentStatus == 'unpaid')
                $followBookingPage->addRenderView('myBookingList', 'booking_list_unpaid_1');
            if ($paymentStatus == 'paid')
                $followBookingPage->addRenderView('myBookingList', 'booking_list_paid_1');
        }

        if ($senderControl->isLinkClicked('cancelPaidBooking_1')) {
            $cartId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('cartId');
            $bookingId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('bookingId');
            $result = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('result');
            $followBookingPage->addRenderView('confirmCancelBooking', 'booking_cancel_paid_1', array(
                'bookingId' => $bookingId,
                'cartId' => $cartId,
                'result' => $result
            ));
        }
        if ($senderControl->isLinkClicked('showBookingDetail_1')) {
            $cartId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('cartId');
            $bookingId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('bookingId');
            $state = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('state');
            $followBookingPage->addRenderView('booking_detail_1', 'booking_detail_1', array(
                'bookingId' => $bookingId,
                'cartId' => $cartId,
                'state' => $state
            ));
        }
        if ($senderControl->isLinkClicked('cancelBookingNow_1')) {
            $transaction_id = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('transaction_id');
            $cartId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('cartId');
            $bookingId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('bookingId');
            $total_fee = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('total_fee');
            $out_refund_no = "1220336601" . time();
            $TotalMoney = $total_fee * 100; //单位换算为元
            /* 商户号 */
            $partner = "1220336601";
            /* 密钥 */
            $key = "89003dcbc62cb9cbdd6a2eb5aded04de";
            /* 创建支付请求对象 */
            $reqHandler = new RequestHandler();
            //通信对象
            $httpClient = new TenpayHttpClient();
            //应答对象
            $resHandler = new ClientResponseHandler();
            //-----------------------------
            //设置请求参数
            //-----------------------------
            $reqHandler->init();
            $reqHandler->setKey($key);
            $reqHandler->setGateUrl("https://mch.tenpay.com/refundapi/gateway/refund.xml");
            $reqHandler->setParameter("partner", $partner);
            $reqHandler->setParameter("transaction_id", $transaction_id);
            //必须保证全局唯一，同个退款单号财付通认为是同笔请求
            $reqHandler->setParameter("out_refund_no", $out_refund_no); //数据更改
            $reqHandler->setParameter("total_fee", $TotalMoney); //数据更改
            $reqHandler->setParameter("refund_fee", $TotalMoney); //数据更改
            $reqHandler->setParameter("op_user_id", "1220336601");
            //操作员密码,MD5处理
            $reqHandler->setParameter("op_user_passwd", md5("hl0701!"));
            //接口版本号,取值1.1
            $reqHandler->setParameter("service_version", "1.1");
            //-----------------------------
            //设置通信参数
            //-----------------------------
            //设置PEM证书，pfx证书转pem方法：openssl pkcs12 -in 2000000501.pfx  -out 2000000501.pem
            //证书必须放在用户下载不到的目录，避免证书被盗取
            $httpClient->setCertInfo(yii::getPathOfAlias('application.application.app.BWeSport.classes') . '\1220336601_20140804170504.pem', "1220336601");
            //设置CA
            $httpClient->setCaInfo(yii::getPathOfAlias('application.application.app.BWeSport.classes') . '\cacert.pem');
            $httpClient->setTimeOut(5);
            //设置请求内容
            $httpClient->setReqContent($reqHandler->getRequestURL());
            if ($httpClient->call()) {
                //设置结果参数
                $resHandler->setContent($httpClient->getResContent());
                $resHandler->setKey($key);

                //判断签名及结果
                //只有签名正确并且retcode为0才是请求成功
                if ($resHandler->isTenpaySign() && $resHandler->getParameter("retcode") == "0") {
                    //取结果参数做业务处理
                    //商户订单号
                    $out_trade_no = $resHandler->getParameter("out_trade_no");
                    //财付通订单号
                    $transaction_id = $resHandler->getParameter("transaction_id");
                    //商户退款单号
                    $out_refund_no = $resHandler->getParameter("out_refund_no");
                    //财付通退款单号
                    $refund_id = $resHandler->getParameter("refund_id");
                    //退款金额,以分为单位
                    $refund_fee = $resHandler->getParameter("refund_fee");
                    //退款状态``````````````````````````````````````````````````````` 
                    $refund_status = $resHandler->getParameter("refund_status");
                    if ($refund_status == 4 || $refund_status == 8 || $refund_status == 9 || $refund_status == 10 || $refund_status == 11) {
                        $result = "success";
                        $cartTable = new BWCart();
                        $inputTable = new BTreeTable('BWInputValue');
                        $cartRow = $cartTable->getListById($cartId);
                        $bookingRow = $inputTable->getListById($bookingId);
                        $bookingRow->addItem('bookingStatus', 'available');
                        $cartRow->addItem('paymentStatus', BCart::Payment_Status_Paid_Cancelled);
                    } else {
                        $result = "Notsuccess";
                    }
//                         echo "OK,refund_status=" . $refund_status . ",out_refund_no=" . $resHandler->getParameter("out_refund_no") . ",refund_fee=" . $resHandler->getParameter("refund_fee") . "<br>";
                } else {
                    $result = "Notsuccess";
                    //错误时，返回结果可能没有签名，记录retcode、retmsg看失败详情。
//                                   echo "验证签名失败 或 业务错误信息:retcode=" . $resHandler->getParameter("retcode"). ",retmsg=" . $resHandler->getParameter("retmsg") . "<br>";
                }
            } else {
                $result = "Notsuccess";
//                        echo "后台调用通信失败，请联系管理员";
//                        echo "call err:" . $httpClient->getResponseCode() ."," . $httpClient->getErrInfo() . "<br>";
                //有可能因为网络原因，请求已经处理，但未收到应答。
            }


            $followBookingPage->addRenderView('confirmCancelBooking_1', 'booking_cancel_paid_1', array(
                'bookingId' => $bookingId,
                'cartId' => $cartId,
                'result' => $result
            ));
        }


        if ($senderControl->isAjaxLinkClicked('addBooking')) {

            $updateControl->addRenderView('addBooking', 'booking_add');
        }

        if ($senderControl->isAjaxLinkClicked('showAddBooking')) {
            //$eventId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('eventId');
            $bookingId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('bookingId');
            $findText = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('findText');
            $findContext = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('findContext');

            $updateControl->addRenderView('booking_add', 'booking_add', array(
                'bookingId' => $bookingId,
                'findText' => $findText
            ));
            //$updateControl->render();
            //Blyn::app()->end();
        }

        if ($senderControl->isAjaxLinkClicked('showBookingList')) {
            //$eventId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('eventId');
            $findText = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('findText');
            $findContext = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('findContext');

            $data = array();
            if ($findText != NULL) {
                $data['findText'] = $findText;
            }
            if ($findContext != NULL) {
                $data['findContext'] = $findContext;
            }

            $updateControl->addRenderView('booking_list', 'booking_list', $data);
        }

        if ($senderControl->isAjaxLinkClicked('showSelectedPageBookingList')) {
            $rowsPerPage = 50;
            $curPageNo = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('curPageNo');
            $findText = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('findText');
            $findContext = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('findContext');
            $newContext = array();
            if (isset($findContext)) {
                if (is_array($findContext)) {
                    $findContext['limitStart'] = ($curPageNo - 1) * $rowsPerPage;
                }
                $newContext = $findContext;
            }
            $availableList = $this->findByFindText($findText, $newContext);
            $updateControl->addRenderView('booking_list', 'booking_list', array('availableList' => $availableList, 'findText' => $findText, 'findContext' => $newContext, 'curPageNo' => $curPageNo));
        }

        if ($senderControl->isAjaxLinkClicked('addBooking')) {
            //$eventId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('eventId');
            $bookingId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('bookingId');
            $bookingListNode = new BWInputValue($bookingId);
            $bookingList = new BTreeList($bookingListNode);

            $bookingStatusItem = $bookingList->getItem('bookingStatus');
            if ($bookingStatusItem instanceof BWInputValue) {
                $bookingStatusItem->value = 'booked';
                $bookingStatusItem->save();

                $bookingList->addItem('bookingUserId', Blyn::app()->getCurrentUser()->getId());
                $bookingList->addItem('bookingTime', time());
            }

            $updateControl->addRenderView('myBookingList', 'booking_list_unpaid', array(
                'bookingId' => $bookingId
            ));
        }

        if ($senderControl->isAjaxLinkClicked('addToBookingCart')) {
            $bookingId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('bookingId');
            $bookingItem = new BWInputValue($bookingId);
            $bookingList = new BTreeList($bookingItem);
            //default unit
            $unit = 'yuan';
            //default quantity
            $quantity = 1;
            $priceItem = $bookingList->getItem('price');
            if ($priceItem instanceof BTreeItem) {
                $price = $priceItem->value;
            }
            $userShoppingCart = new BWCart();
            $userShoppingCart->addList(array(
                'paymentStatus' => BWCart::Payment_Status_Not_Paid,
                'productName' => $bookingList->getName(),
                'productId' => $bookingId,
                'price' => $price,
                'quantity' => $quantity,
                'addToBookingCartTime' => time(),
                'moneyUnit' => $unit));

            //change booking status
            $bookingList->addItem('addToBookingCartTime', time());

            $updateControl->addRenderView('toggleButton', 'booking_add_toggleButton', array('bookingStatus' => 'booking', 'bookingId' => $bookingId));
        }

        if ($senderControl->isAjaxLinkClicked('showPayBooking')) {
            $updateControl->addRenderView('payBookingList', 'booking_list_unpaid');
        }

        if ($senderControl->isAjaxLinkClicked('payBooking')) {
            //$paidMoney = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('paidMoney');
            //$paidCount = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('paidCount');
            $paidMoney = 0;
            $paidCount = 0;
            $cartTable = new BWCart();
            if (!empty($_POST)) {
                $checkedArray = $_POST['checkbox'];
                $paidCount = count($checkedArray);
                foreach ($checkedArray as $cartId) {
                    if ($cartId != NULL) {
                        $cart = $cartTable->getListById($cartId);
                        $price = $cart->getItem('price')->value;
                        $quantity = $cart->getItem('quantity')->value;
                        $cart->addItem('paymentStatus', BCart::Payment_Status_Waiting_Paid);
                        $paidMoney += $price * $quantity;
                    }
                }
            }

            $updateControl->addRenderView('payBooking', 'booking_pay_view', array('paidMoney' => $paidMoney, 'paidCount' => $paidCount));
        }

        if ($senderControl->isAjaxLinkClicked('payNow')) {
            $paidMoney = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('paidMoney');
            $paidCount = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('paidCount');
            $transactionTable = new BWTransaction();

            $transaction = $transactionTable->addList(array(
                'payerId' => Blyn::app()->getCurrentUser()->getId(),
                'paidTime' => time(),
                'cartItemNumber' => $paidCount,
                'paidMoney' => $paidMoney
            ));
            $transactionId = $transaction->getId();

            $bookingCart = new BWCart();
            $view = $bookingCart->getView(array('itemData' => array('paymentStatus' => bcart::Payment_Status_Waiting_Paid)));
            foreach ($view as $cartList) {
                if ($cartList instanceof BTreeList) {
                    $cartList->addItem('paymentStatus', BCart::Payment_Status_Paid);
                    $cartList->addItem('payerId', Blyn::app()->getCurrentUser()->getId());
                    $cartList->addItem('paidTime', time());
                    $cartList->addItem('transactionId', $transactionId);
                    //below update status for booking value
                    $bookingValueId = $cartList->getItem('productId')->getValue();
                    $bookingValueItem = new BWInputValue($bookingValueId);
                    $bookingList = new BTreeList($bookingValueItem);
                    $bookingList->addItem('bookingStatus', 'paid');
                    $bookingList->addItem('payerId', Blyn::app()->getCurrentUser()->getId());
                    $bookingList->addItem('paidTime', time());
                    $bookingList->addItem('transactionId', $transactionId);
                }
            }

            $updateControl->addRenderView('payBooking', 'booking_pay', array(
                'transactionId' => $transactionId,
                'paidMoney' => $paidMoney,
                'paidCount' => $paidCount));
            //$updateControl->render();
            //Blyn::app()->end();
        }

        if ($senderControl->isAjaxLinkClicked('showMyBooking')) {
            $updateControl->setViews(NULL);
            $updateControl->addRenderView('myBooking', 'booking_list_unpaid');
        }

        if ($senderControl->isAjaxLinkClicked('showMyBookingList')) {
            $paymentStatus = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('paymentStatus');
            if ($paymentStatus == 'unpaid')
                $updateControl->addRenderView('myBookingList', 'booking_list_unpaid');
            if ($paymentStatus == 'paid')
                $updateControl->addRenderView('myBookingList', 'booking_list_paid');
        }

        if ($senderControl->isAjaxLinkClicked('cancelPaidBooking')) {
            //$eventId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('eventId');
            $cartId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('cartId');
            $bookingId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('bookingId');

            $updateControl->addRenderView('confirmCancelBooking', 'booking_cancel_paid', array(
                'bookingId' => $bookingId,
                'cartId' => $cartId
            ));
        }

        if ($senderControl->isAjaxLinkClicked('cancelBookingNow')) {
            //$eventId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('eventId');
            $cartId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('cartId');
            $bookingId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('bookingId');

            $cartTable = new BWCart();
            $inputTable = new BTreeTable('BWInputValue');
            $cartRow = $cartTable->getListById($cartId);
            $bookingRow = $inputTable->getListById($bookingId);

            //first change status for booking 
            $bookingRow->addItem('bookingStatus', 'available');

            //change status for cart
            $cartRow->addItem('paymentStatus', BCart::Payment_Status_Paid_Cancelled);

            //execute transaction  for cancel

            $updateControl->addRenderView('confirmCancelBooking', 'booking_cancel_paid', array(
                'bookingId' => $bookingId,
                'cartId' => $cartId
            ));
        }

        if ($senderControl->isAjaxLinkClicked('showBookingDetail')) {
            $control = new BUIControl('temp');
            $cartId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('cartId');
            $bookingId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('bookingId');
            $control->addRenderView('showBookingDetail', 'booking_detail', array('cartId' => $cartId, 'bookingId' => $bookingId));
            $control->render();
            Blyn::app()->end();
        }

        if ($senderControl->isAjaxLinkClicked('deleteUnpaidBooking')) {
            $cartId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('cartId');
            $cartTable = new BWCart();
            $bookingTable = new BTreeTable('BWInputValue');
            if (is_numeric($cartId) && $cartId > 0) {
                $cartList = $cartTable->getListById($cartId);
                $cartList->addItem('paymentStatus', bcart::Payment_Status_Paid_Cancelled);
                $bookingId = $cartList->getItem('productId')->value;
                $bookingList = $bookingTable->getListById($bookingId);
                $bookingList->addItem('addToBookingCartTime', 0);
            } else {
                if (!empty($_POST)) {
                    $checkedArray = $_POST['checkbox'];
                    foreach ($checkedArray as $cartId) {
                        if ($cartId != NULL) {
                            $cartList = $cartTable->getListById($cartId);
                            $cartList->addItem('paymentStatus', bcart::Payment_Status_Paid_Cancelled);
                            $bookingId = $cartList->getItem('productId')->value;
                            $bookingList = $bookingTable->getListById($bookingId);
                            $bookingList->addItem('addToBookingCartTime', 0);
                        }
                    }
                }
            }
            $updateControl->addRenderView('booking_list_unpaid');
        }

        //for link from mobile, first link should be general link, for example
        //this link can be a menu link in wechat group
        if ($senderControl->isLinkClicked('testWxAjaxLink')) {
            $screen = Blyn::app()->getUIManager()->getCurrentScreen();
            //please add entry page as below, you can put your first page 
            //into a BUIControl and then use bilyn ajax framework as usual
            $wxControl = new BUIWXControl('page');
            $wxControl->addRenderView('testAjaxLink1');
            //must add your wxcontrol into screen
            $screen->addChildControl($wxControl);
        }
        /*
          if($senderControl->isAjaxLinkClicked('testWxAjaxLink')){
          $updateControl = Blyn::app()->getUIManager()->getUpdateControl();
          }
         * 
         */

        //after add wxcontrol into first link, then can use ajax link as usual
        if ($senderControl->isAjaxLinkClicked('goTo_testAjaxLink2')) {
            $updateControl->addRenderView('testAjaxLink2');
        }

        $screen = Blyn::app()->getUIManager()->getCurrentScreen();
        $wxControl = new BUIWXControl('manageBooking');
        $membershipControl = new BUIMembership('membership');
        $wxControl->addChildControl($membershipControl);
        $screen->addChildControl($wxControl);
        if ($wxControl->isLinkClicked('manageBooking')) {            
            //$wxControl = new BUIWXControl('page');
            //$wxControl->addRenderView('manageBooking_login');
            //$screen->addChildControl($wxControl);

            $user = Blyn::app()->getCurrentUser();
            $space = $this->getCurrentSpace();
            $memberRole = $space->getSpaceEngine()->getRole(BRole::Role_App_Member);
            $adminRole = $space->getSpaceEngine()->getRole(BRole::Role_App_Admin);
            if ($user->isMemberOf($memberRole) || $user->isMemberOf($adminRole)) {
//            if ($user->isMemberOfRolesNew(BRole::Role_Space_Member, $this->getCurrentSpace())) 
                $wxControl->addRenderView('manageBooking_index');
            } 
        }

        //add userControl under current screen
        $userControl = new BUIUser('userInfo');
        $screen = Blyn::app()->getUIManager()->getCurrentScreen();
        $screen->addChildControl($userControl);
    }

    public function runAdminBooking($operation = NULL, $data = NULL) {

        $updateControl = Blyn::app()->getUIManager()->getUpdateControl();
        $senderControl = Blyn::app()->getUIManager()->getSenderControl();
        $processData = new BWProcessData();


        if ($senderControl->isAjaxLinkClicked('showAddEvent')) {
            $eventId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('eventId');
            //$control = new BUIControl();
            $updateControl->addRenderView('addEventView', 'event_add', array('eventId' => $eventId));
            //$updateControl->render();
            //$control->render();
            //Blyn::app()->end();
        }
        if ($senderControl->isAjaxLinkClicked('showAddCourt')) {
            $eventId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('eventId');
            $bookableId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('bookableId');
            $courtId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('courtId');
            $updateControl->addRenderView('bookableaddcourt', 'bookable_add_court', array(
                'eventId' => $eventId,
                'bookableId' => $bookableId,
                'courtId' => $courtId
            ));
        }

        if ($senderControl->isAjaxLinkClicked('showAddTimeSlot')) {
            $eventId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('eventId');
            $bookableId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('bookableId');
            $timeslotId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('timeSlotId');
            $updateControl->addRenderView('bookableAddTimeslot', 'bookable_add_timeslot', array(
                'eventId' => $eventId,
                'bookableId' => $bookableId,
                'timeSlotId' => $timeslotId
            ));
            //$updateControl->render();
            //Blyn::app()->end();
        }

        if ($senderControl->isAjaxLinkClicked('showBookableList')) {
            $eventId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('eventId');
            $updateControl->addRenderView('bookableList', 'bookable_list', array('eventId' => $eventId));
            //Blyn::app()->getUIManager()->getCurrentScreen()->addControl($updateControl);
            //$updateControl->render();
            //Blyn::app()->end();
        }

        if ($senderControl->isAjaxLinkClicked('showAddBookable')) {
            $eventId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('eventId');
            $bookableId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('bookableId');

            if ($bookableId == NULL || $bookableId == 0) {
                $bookableMessage = new BWMessage();
                $bookableMessage->name = 'bookable' . time();
                $bookableMessage->save();
                $bookableId = $bookableMessage->getId();
            }
            $updateControl->addRenderView('bookable_add', 'bookable_add', array(
                'eventId' => $eventId,
                'bookableId' => $bookableId
            ));
            //$updateControl->render();
            //Blyn::app()->end();
        }

        if ($senderControl->isAjaxLinkClicked('showEventList')) {
            $eventLit = $this->getEventList();
            $updateControl->addRenderView('eventList', 'event_list', array('eventList' => $eventLit));
            //$updateControl->render();
            //Blyn::app()->end();
        }

        if ($senderControl->isAjaxLinkClicked('saveBookable')) {
            $bookableId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('bookableId');
            $eventId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('eventId');
            $modelName = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('postModel');

            $postData = $processData->parsedModelData($modelName);

            //first populate bookable message for new or modified message
            $bookableMessage = NULL;
            if (is_numeric($bookableId) && $bookableId > 0) {
                $messageList = $processData->populateMessageListFromPostData($postData, 'vender');
                $bookableMessage = reset($messageList);
                $bookableMessage->id = $bookableId;
                $bookableMessage->save();
            } else {
                //$messageList = $processData->populateMessageListFromPostData($postData, 'vender');
                //$bookableMessage = reset($messageList);
                $bookableMessage = new BWMessage();
                $bookableMessage->name = uniqid('b');
                $bookableMessage->save();
                $bookableMessage->name = 'bookable' . $bookableMessage->getId();
                $bookableMessage->save();
            }

            $event = new BWEvent($eventId);
            $vender = $event->getMessageManager()->getMessage('vender');
            $vender->getMessageManager()->addMessage($bookableMessage);


            $bookableMessage->addAttribute('eventId', $event->getId());
            $bookableMessage->addAttribute('eventName', $event->getName());
            $bookableMessage->addAttribute('venderId', $vender->getId());
            $bookableMessage->addAttribute('venderName', $vender->getName());

            //populate medias for bookable message for both new or modified
            $mediaList = $processData->populateMediaListFromPostData($postData, 'message_bookable');

            foreach ($mediaList as $media) {
                //$media->save();
                //if ($bookableId == 0) {
                $bookableMessage->getMediaManager()->addMedia($media);
                //}
            }

            //populate city for bookable
            $region = $bookableMessage->getMediaManager()->getMedia('region')->getContent();
            $address = BWAddress::getRoot()->getChild($region);
            if ($address instanceof BWAddress) {
                $city = $address->getParent();
                $cityMedia = new BWMedia();
                $cityMedia->name = 'city';
                $cityMedia->content = $city->getFullName();
                $bookableMessage->getMediaManager()->addMedia($cityMedia);
            }

            //populate inputmedia for bookable message
            //$inputMediaList = $processData->populateInputMediaListFromPostData($postData, NULL, $bookableMessage);
            //foreach ($inputMediaList as $inputMedia) {
            //$bookableMessage->getInputMediaManager()->addInputMedia($inputMedia);
            //}
            //each time when change bookale, re-populate court
            //$courtInputMedia = $bookableMessage->getInputMediaManager()->getInputMedia('court');
            //$courtMessageList = $courtInputMedia->getMessageManager()->getMessageList();
            //$this->populateCourtInputable($courtMessageList, $courtInputMedia);
            //update inputvalue after change bookable, it may take some time
            $this->updateBookableInputValue($bookableMessage);

            $updateControl->addRenderView('bookable_list', 'bookable_list', array('eventId' => $eventId));
        }

        if ($senderControl->isAjaxLinkClicked('saveEvent')) {
            $modelName = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('postModel');
            $eventId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('eventId');
            $postData = $processData->parsedModelData($modelName);
            if (is_numeric($eventId) && $eventId > 0) {
                $event = new BWEvent($eventId);
                $event = $processData->populateEventFromPostData($postData, NULL, $event);
                $event->save();
            } else {
                $event = $processData->populateEventFromPostData($postData);
                $event->save();
                $eventType = $processData->populateEventTypeFromPostData($postData);
                if ($eventType instanceof BWEventGroup) {
                    $eventType->addMember($event);
                }
            }

            $mediaList = $processData->populateMediaListFromPostData($postData, 'event');

            //save media to event
            foreach ($mediaList as $media) {
                $event->getMediaManager()->addMedia($media);
            }

            $inputMediaList = $processData->populateInputMediaListFromPostData($postData, 'event', $event);

            //save inputMedia to event
            foreach ($inputMediaList as $iMedia) {
                $event->getInputMediaManager()->addInputMedia($iMedia);
            }

            //save vender message
            $venderMessageList = $processData->populateMessageListFromPostData($postData);
            $venderMessage = reset($venderMessageList);
            if ($venderMessage instanceof BWMessage) {
                $venderMessage->name = 'vender';
                $venderMessage->setOwner($event);
                $venderMessage->save();

                //add message into event
                $event->getMessageManager()->addMessage($venderMessage);

                //save media
                $mediaList = $processData->populateMediaListFromPostData($postData, 'vender');
                //save media to event
                foreach ($mediaList as $media) {
                    $venderMessage->getMediaManager()->addMedia($media);
                }

                $inputMediaList = $processData->populateInputMediaListFromPostData($postData, 'vender', $venderMessage);

                //save inputMedia to event
                foreach ($inputMediaList as $iMedia) {
                    $venderMessage->getInputMediaManager()->addInputMedia($iMedia);
                }
            }

            if (!$updateControl instanceof BUIScreen) {
                $updateControl->addRenderView('eventList', 'event_list', array('eventList' => $this->getEventList()));
            }
            $updateControl->render();
            Blyn::app()->end();
            return;
        }

        if ($senderControl->isAjaxLinkClicked('addBookableCourt')) {
            $modelName = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('postModel');
            $bookableId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('bookableId');
            $eventId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('eventId');
            $inputMediaId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('inputMediaId');
            $courtId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('courtId');

            if (is_numeric($bookableId) && $bookableId > 0)
                $bookableMessage = new BWMessage($bookableId);

            if ($bookableMessage != NULL) {
                $inputMedia = $bookableMessage->getInputMediaManager()->getInputMedia('court');
                $postData = $processData->parsedModelData($modelName);
                $inputMediaCourtMediaList = $processData->populateMediaListFromPostData($postData, 'inputMedia_court');
                $courtTypeMedia = reset($inputMediaCourtMediaList);
                $courtMediaList = $processData->populateMediaListFromPostData($postData, 'message_court');

                if (is_numeric($courtId) && $courtId > 0) {
                    $courtMessage = new BWMessage($courtId);
                } else {
                    $courtMessage = new BWMessage();
                    $courtMessage->name = uniqid('c');
                    $courtMessage->save();
                    $courtMessage->name = 'court' . $courtMessage->getId();
                    $courtMessage->save();
                    $inputMedia->getMessageManager()->addMessage($courtMessage);
                    $courtId = $courtMessage->getId();
                }

                foreach ($courtMediaList as $media) {
                    $courtMessage->getMediaManager()->addMedia($media);
                }

                $courtName = $courtMessage->getName();

                $inputType = $inputMedia->getInputType();
                if ($inputType instanceof BWKeyValueType) {
                    $inputable = $inputType->addInputable('court' . $courtId, $courtName);
                    foreach ($courtMediaList as $media) {
                        if ($media->name == 'displayName') {
                            $displayName = $media->getContent();
                            $inputable->addAttribute('displayName', $displayName);
                        }
                        if ($media->name == 'address') {
                            $address = $media->getContent();
                            $inputable->addAttribute('address', $address);
                        }
                        if ($media->name == 'image') {
                            $image = $media->getContent();
                            $inputable->addAttribute('image', $image);
                        }
                        if ($media->name == 'description') {
                            $description = $media->getContent();
                            $inputable->addAttribute('description', $description);
                        }
                    }
                }
            }

            //$control = new BUIControl('showBookableList');
            //$updateControl->setViews(NULL);

            $updateControl->addRenderView('courtlist', 'bookable_add_courtList', array(
                'courtInputMediaId' => $inputMedia->getId(),
                'bookableId' => $bookableId,
                'eventId' => $eventId
            ));

            //$updateControl->render();
            //Blyn::app()->end();
        }

        if ($senderControl->isAjaxLinkClicked('addBookableTimeSlot')) {
            $modelName = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('postModel');
            $bookableId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('bookableId');
            $eventId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('eventId');
            $inputMediaId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('inputMediaId');
            $timeslotId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('timeSlotId');

            if (is_numeric($bookableId) && $bookableId > 0)
                $bookableMessage = new BWMessage($bookableId);

            if ($bookableMessage != NULL) {
                $inputMedia = $bookableMessage->getInputMediaManager()->getInputMedia('timeSlot');
                $postData = $processData->parsedModelData($modelName);
                $inputTypeMediaList = $processData->populateMediaListFromPostData($postData, 'inputType_timeSlot');
                $inputType = $inputMedia->getInputType();

                foreach ($inputTypeMediaList as $media) {
                    $inputType->getMediaManager()->addMedia($media);
                }

                if (is_numeric($timeslotId) && $timeslotId > 0) {
                    $configMessage = new BWMessage($timeslotId);
                } else {
                    $configMessage = new BWMessage();
                    $configMessage->name = uniqid('t');
                    $configMessage->save();
                    $configMessage->name = 'timeSlot' . $configMessage->getId();
                    $configMessage->save();
                    $inputMedia->getMessageManager()->addMessage($configMessage);
                }

                if ($configMessage instanceof BWMessage) {
                    $courtMediaList = $processData->populateMediaListFromPostData($postData, 'message_inputableConfig');
                    foreach ($courtMediaList as $media) {
                        $configMessage->getMediaManager()->addMedia($media);
                    }
                }
            }

            $updateControl->addRenderView('timeSlotlist', 'bookable_add_timeslotList', array(
                'bookableId' => $bookableId,
                'eventId' => $eventId
            ));

            //$updateControl->render();
            //Blyn::app()->end();
        }

        /*
          if ($senderControl->isAjaxLinkClicked('addMoreTimeSlot')) {
          $modelName = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('postModel');
          $bookableId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('bookableId');
          $eventId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('eventId');
          $inputMediaId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('inputMediaId');

          $postData = $processData->parsedModelData($modelName);

          $inputMedia = NULL;

          if (is_numeric($inputMediaId) && $inputMediaId > 0) {
          $inputMedia = new BWInputMedia($inputMediaId);
          } else {
          $inputMediaList = $processData->populateInputMediaListFromPostData($postData);
          foreach ($inputMediaList as $iMedia) {
          if ($iMedia->getName() == 'timeSlot') {
          $inputMedia = $iMedia;
          break;
          }
          }
          }

          $updateControl->addRenderView('showAddTimeSlot', 'bookable_add_timeslot', array(
          'eventId' => $eventId,
          'bookableId' => $bookableId,
          'inputMediaId' => $inputMediaId
          ));
          }
         * 
         */

        if ($senderControl->isAjaxLinkClicked('showBookingAvailable')) {
            $eventId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('eventId');
            $event = new BWEvent($eventId);
            $vender = $event->getMessageManager()->getMessage('vender');
            $venderId = $vender->getMediaManager()->getMedia('venderId')->getContent();

            $valueList = $this->findInputValueListByVender(array('venderId' => $venderId));

            $updateControl->addRenderView('booking_list', 'booking_list_available', array('eventId' => $eventId,
                'bookingList' => $valueList));
            //$bookableList = $vender->getMessageManager()->getMessageList();

            /*
              foreach ($bookableList as $bookableId => $bookable) {
              $this->updateBookableData($bookableId);
              $inputValueTable = $bookable->getInputValueManager()->getInputValueTable('booking');
              }
             * 
             */
        }

        if ($senderControl->isAjaxLinkClicked('deleteEvent')) {
            $eventId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('eventId');
            if ($eventId != NULL) {
                //$event = new BWEvent($eventId);
                BWEvent::delete($eventId);
            }

//            $updateControl->addRenderView('event_list');
            $updateControl->addRenderView('eventList', 'event_list', array('eventList' => $this->getEventList()));
        }

        if ($senderControl->isAjaxLinkClicked('deleteSelectedEvent')) {
            if (!empty($_POST)) {
                $checkedArray = $_POST['checkbox'];

                foreach ($checkedArray as $eventId) {
                    if ($eventId != NULL) {
                        //$event = new BWEvent($eventId);
                        BWEvent::delete($eventId);
                    }
                }
            }

//            $updateControl->addRenderView('event_list');
            $updateControl->addRenderView('eventList', 'event_list', array('eventList' => $this->getEventList()));
        }

        if ($senderControl->isAjaxLinkClicked('deleteBookable')) {
            $eventId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('eventId');
            $bookableId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('bookableId');

            if ($eventId != NULL && $bookableId != NULL) {
                BWMessage::delete($bookableId);
            }

            $updateControl->addRenderView('bookableList', 'bookable_list', array('eventId' => $eventId));
        }

        if ($senderControl->isAjaxLinkClicked('deleteCheckedBookable')) {
            $eventId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('eventId');

            if ($eventId != NULL && !empty($_POST)) {
                $checkedArray = $_POST['checkbox'];

                foreach ($checkedArray as $bookableId) {
                    if ($bookableId != NULL) {
                        BWMessage::delete($bookableId);
                    }
                }
            }

            $updateControl->addRenderView('bookableList', 'bookable_list', array('eventId' => $eventId));
        }

        if ($senderControl->isAjaxLinkClicked('deleteTimeSlot')) {
            $eventId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('eventId');
            $bookableId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('bookableId');

            $timeSlotId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('timeSlotId');
            if ($bookableId != NULL && $timeSlotId != NULL) {
                $bookableMessage = new BWMessage($bookableId);
                $timeSlotInputMedia = $bookableMessage->getInputMediaManager()->getInputMedia('timeSlot');
                $timeSlotInputMedia->getMessageManager()->removeMessage($timeSlotId);
            }

            $updateControl->addRenderView('showTimeSlotList', 'bookable_add_timeslotList', array(
                'eventId' => $eventId,
                'bookableId' => $bookableId,
            ));
        }

        if ($senderControl->isAjaxLinkClicked('deleteCheckedTimeSlot')) {
            $eventId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('eventId');
            $bookableId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('bookableId');

            if (!empty($_POST)) {
                $checkedArray = $_POST['checkbox'];

                foreach ($checkedArray as $timeSlotId) {
                    if ($timeSlotId != NULL) {
                        if ($bookableId != NULL && $timeSlotId != NULL) {
                            $bookableMessage = new BWMessage($bookableId);
                            $timeSlotInputMedia = $bookableMessage->getInputMediaManager()->getInputMedia('timeSlot');
                            $timeSlotInputMedia->getMessageManager()->removeMessage($timeSlotId);
                        }
                    }
                }
            }

            $updateControl->addRenderView('showTimeSlotList', 'bookable_add_timeslotList', array(
                'eventId' => $eventId,
                'bookableId' => $bookableId,
            ));
        }

        if ($senderControl->isAjaxLinkClicked('deleteCheckedCourt')) {
            $eventId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('eventId');
            $bookableId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('bookableId');

            if (!empty($_POST)) {
                $checkedArray = $_POST['checkbox'];

                foreach ($checkedArray as $courtId) {
                    if ($courtId != NULL) {
                        if ($bookableId != NULL && $courtId != NULL) {
                            $bookableMessage = new BWMessage($bookableId);
                            $courtInputMedia = $bookableMessage->getInputMediaManager()->getInputMedia('court');
                            $courtInputMedia->getMessageManager()->removeMessage($courtId);
                        }
                    }
                }
            }

            $updateControl->addRenderView('showCourtList', 'bookable_add_courtList', array(
                'eventId' => $eventId,
                'bookableId' => $bookableId,
            ));
        }

        if ($senderControl->isAjaxLinkClicked('deleteCourt')) {
            $eventId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('eventId');
            $bookableId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('bookableId');

            $courtId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('courtId');
            if ($bookableId != NULL && $courtId != NULL) {
                $bookableMessage = new BWMessage($bookableId);
                $courtInputMedia = $bookableMessage->getInputMediaManager()->getInputMedia('court');
                $courtInputMedia->getMessageManager()->removeMessage($courtId);
            }

            $updateControl->addRenderView('showCourtList', 'bookable_add_courtList', array(
                'eventId' => $eventId,
                'bookableId' => $bookableId,
            ));
        }

        if ($senderControl->isAjaxLinkClicked('showManageBookingList')) {
            $bookableId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('bookableId');
            $eventId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('eventId');

            $app = Blyn::app()->getActiveApp();
            $bookingList = NULL;
            $data = array();
            if (is_numeric($eventId) && $eventId > 0) {
                $event = new BWEvent($eventId);
                $vender = $event->getMessageManager()->getMessage('vender');
                $bookingList = $app->findByFindText('venderId=' . $vender->getId());
                $data['eventId'] = $eventId;
            }
            if (is_numeric($bookableId) && $bookableId > 0) {
                $bookingList = $app->findByFindText('bookableId=' . $bookableId);
                $data['bookableId'] = $bookableId;
            }
            $data['availableList'] = $bookingList;

            $updateControl->addRenderView('manageBookingList', 'booking_list_manage', $data);
        }
    }

    public function runManageBooking($operation = NULL, $data = NULL) {
        $updateControl = Blyn::app()->getUIManager()->getUpdateControl();
        $senderControl = Blyn::app()->getUIManager()->getSenderControl();
        $currentScreen = Blyn::app()->getUIManager()->getCurrentScreen();
        $wxMenu = new BUIWXMenu(Blyn::app()->getActiveOperation());
        $manageBookingPage = new BUIWXControl('manageBooking');
        $currentScreen->addChildControl($manageBookingPage);
        $processData = new BWProcessData();
        $postData = $processData->parsedModelData();
//         if ($wxMenu->isMenuClicked('managebooking')) {
//            $manageBookingPage->addRenderView('booking_find_1', 'booking_find_1', array('controlPanel' => 'search'));
//        }
//        $memberControl = new BControlMemeber();
//        $currentScreen->addChildControl($memberControl);

        if ($senderControl->isAjaxLinkClicked('showBookingDetail')) {
            $control = new BUIControl('temp');
            $cartId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('cartId');
            $bookingId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('bookingId');
            $control->addRenderView('showBookingDetail', 'booking_detail', array('cartId' => $cartId, 'bookingId' => $bookingId));
            $control->render();
            Blyn::app()->end();
        }
        $wxControl = new BUIWXControl('manageBooking');
        if ($wxControl->isLinkClicked('manageBooking')) {
            $screen = Blyn::app()->getUIManager()->getCurrentScreen();
            $wxControl = new BUIWXControl('page');
            //$wxControl->addRenderView('manageBooking_login');
            $screen->addChildControl($wxControl);

            $user = Blyn::app()->getCurrentUser();
            $space = $this->getCurrentSpace();
            $memberRole = $space->getSpaceEngine()->getRole(BRole::Role_App_Member);
            $adminRole = $space->getSpaceEngine()->getRole(BRole::Role_App_Admin);
            if ($user->isMemberOf($memberRole) || $user->isMemberOf($adminRole)) {
//            if ($user->isMemberOfRolesNew(BRole::Role_Space_Member, $this->getCurrentSpace())) 
                $wxControl->addRenderView('manageBooking_index');
            } else {
                $wxControl->addRenderView('manageBooking_applyForMember');
            }
        }
        if ($senderControl->isLinkClicked('manageBooking')) {
            $screen = Blyn::app()->getUIManager()->getCurrentScreen();
            $wxControl = new BUIWXControl('page');
            //$wxControl->addRenderView('manageBooking_login');
            $screen->addChildControl($wxControl);
            $wxControl->addRenderView('manageBooking_index');
        }

        if ($senderControl->isAjaxLinkClicked('manageBooking')) {
            $updateControl->addRenderView('manageBooking', 'manageBooking_index', array());
        }

        if ($senderControl->isAjaxLinkClicked('manageBooking_bookingList')) {
            $findText = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('findText');
            $flagText = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('flagText');
            $updateControl->addRenderView('manageBooking_bookingList', 'manageBooking_bookingList', array('flagText' => $flagText, 'findText' => $findText));
        }

        if ($senderControl->isAjaxLinkClicked('manageBooking_remainList')) {
            $findText = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('findText');
            $flagText = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('flagText');
            $updateControl->addRenderView('manageBooking_remainList', 'manageBooking_remainList', array('flagText' => $flagText, 'findText' => $findText));
        }

        if ($senderControl->isAjaxLinkClicked('manageBooking_bookingDetail')) {
            $findText = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('findText');
            $flagText = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('flagText');
            $cartId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('cartId');
            $bookingId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('bookingId');
            $data = array('findText' => $findText, 'flagText' => $flagText, 'cartId' => $cartId, 'bookingId' => $bookingId);
            $updateControl->addRenderView('manageBooking_bookingDetail', 'manageBooking_bookingDetail', $data);
        }

        if ($senderControl->isAjaxLinkClicked('manageBooking_remainDetail')) {
            $findText = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('findText');
            $flagText = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('flagText');
            $bookingId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('bookingId');
            $data = array('findText' => $findText, 'flagText' => $flagText, 'bookingId' => $bookingId);
            $updateControl->addRenderView('manageBooking_remainDetail', 'manageBooking_remainDetail', $data);
        }

        if ($senderControl->isAjaxLinkClicked('manageBooking_selectTime')) {
            $findText = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('findText');
            $flagText = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('flagText');
            $backPage = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('backPage');
            $data = array('findText' => $findText, 'flagText' => $flagText, 'backPage' => $backPage);
            $updateControl->addRenderView('manageBooking_selectTime', 'manageBooking_selectTime', $data);
        }

        if ($senderControl->isAjaxLinkClicked('manageBooking_applyMember')) {
            $mediaList = $processData->populateMediaListFromPostData($postData, 'applyMember_info');

            $userData = array();
            foreach ($mediaList as $media) {
                if ($media->name == 'email') {
                    $userData['email'] = $media->content;
                }
                if ($media->name == 'name') {
                    $userData['name'] = $media->content;
                }
                if ($media->name == 'password') {
                    $userData['password'] = $media->content;
                }
            }

            //first change email and password for user       
            $user = Blyn::app()->getCurrentUser();

            $isChangeUser = FALSE;
            if (isset($userData['email']) && $userData['email'] != NULL) {
                $user->email = $userData['email'];
                $isChangeUser = TRUE;
            }
            if (isset($userData['password']) && $userData['password'] != NULL) {
                $openId = $user->getAttribute('wxOpenId');
                if ($openId != NULL) {
                    $isOk = $user->changePassword($openId, $userData['password']);
                    if ($isOk) {
                        $user->addAttribute('changeWechatPassword', $userData['password']);
                        $isChangeUser = TRUE;
                    }
                }
            }

            if ($isChangeUser) {
                $user->save();
            }

            //below send message
            $userData['userId'] = $user->id;
            $userData['role'] = "member";
            $personalApp = $user->getPersonalSpace()->getAppByName('BPersonalApp');
            $personalApp->getOperation('applyJoinSpace')->getMessenger()->
                    sendMessage('applyJoinSpace', NULL, $userData);

            $updateControl->addRenderView('bookingManagement_afterApply');
        }
    }

    public function getEventTypeList($data = NULL) {
        if ($this->eventTypeList == NULL)
            $this->eventTypeList = BWEventGroup::getRoot()->getChild('type')->getChildrenAsLeaf();

        if (is_string($data) && strtolower($data) == 'fullname') {
            $list = array();
            foreach ($this->eventTypeList as $id => $type) {
                $name = $type->getFullName('|');
                //remove 'type|' in full name
                $name = substr($name, 5);
                $list[$id] = $name;
            }
            return $list;
        }
        return $this->eventTypeList;
    }

    public function getMessageListViewByEventType($eventType) {

        $eventTypeId = NULL;

        if ($eventType instanceof BWEventGroup)
            $eventTypeId = $eventType->getId();

        if (is_string($eventType)) {
            $eventType = BWEventGroup::find($eventType);
            if ($eventType instanceof BWEventGroup)
                $eventTypeId = $eventType->getId();
        }

        if (is_numeric($eventType))
            $eventTypeId = $eventType;

        if (isset($this->messageListViewByEventType[$eventTypeId]))
            return $this->messageListViewByEventType[$eventTypeId];

        return FALSE;
    }

    public function findEventList($findContext = NULL, $onlyPermitted = TRUE) {

        if ($findContext == NULL) {
            $eventList = BWEvent::findAll();
            return $eventList;
        }

        $eventList = arra();

        if (is_array($findContext)) {
            //find by type
            if (isset($findContext['type'])) {
                $type = $findContext['type'];
                unset($findContext['type']);
                if (is_string($type)) {
                    $type = BWEventGroup::find($type);
                }
                if ($type instanceof BWEventGroup) {
                    $eventList = $type->getMembers($findContext);
                    //return $eventList;
                }
            }
        }
    }

    public function getCourtTypeList($data = NULL) {
        return array(
            'soccer_court_11' => '11人制足球场地',
            'soccer_court_7' => '7人制足球场地',
            'soccer_court_5' => '5人制足球场地',
            'badminton_court' => '羽毛球场地'
        );
    }

    public function getRegionList($regionParent = NULL) {

        $regionChongQing = BWAddress::getRoot()->getChild('china.chongqing');

        if ($regionChongQing == NULL) {
            $regionChongQing = BWAddress::getRoot()->addChild('china.chongqing');
        }

        if ($regionChongQing->getChild('banan') == NULL) {
            $regionChongQing->addChild(array('name' => 'banan', 'value' => '巴南区'));
            $regionChongQing->addChild(array('name' => 'yuzhong', 'value' => '渝中区'));
            $regionChongQing->addChild(array('name' => 'shapingba', 'value' => '沙坪坝'));
        }

        $region = BWAddress::getRoot()->getChild($regionParent);

        $list = array();
        if ($region instanceof BWAddress) {
            $children = $region->getChildren();
            foreach ($children as $id => $address) {
                $fullName = $address->getFullName();
                $list[$fullName] = $address->getValue();
            }
        }
        return $list;
    }

    public function populateCourtInputable($courtMessageList = array(), $inputMedia = NULL) {

        $inputType = NULL;
        if ($inputMedia instanceof BWInputMedia) {
            $inputType = $inputMedia->getInputType();
        }

        foreach ($courtMessageList as $courtMessage) {
            $courtId = $courtMessage->name;
            $courtName = $courtMessage->description;
            $courtAddress = $courtMessage->getMediaManager()->getMedia('address');
            $courtDescription = $courtMessage->getMediaManager()->getMedia('description');
            if ($inputType instanceof BWKeyValueType) {
                $inputType->addInputable($courtId, $courtName);
            }
        }
    }

    /**
     * 
     * @param type $findContext
     * @param type $eventType
     * @return type, array of bookingValue list, to get item(cell), please follow 
     * below code:
     * 
     * foreach ($valueList as $list){
     *  if($list instance of BTreeList){
     *  $bookingStatus = $list->getItem('bookingStatus')->value;
     *  $startTime = $list->getItem('startTime')->value;
     *  $endTime = $list->getItem('endTime')->value;
     *  $bookingStartTime = $list->getItem('bookingStartTime')->value;
     *  $bookingEndTime = $list->getItem('bookingEndTime')->value;
     * }
     * 
     * please refer to code in proteccted\application\app\BWeSport\ui\themes\pc_bootstrap\views\booking_list.php
     * for usage of bookValue list
     */
    public function findInputValueListByVender($findContext, $eventType = 'booking.court') {

        $findVenderId = NULL;
        $findVenderName = NULL;
        //$finalInputValueList = array();
        $finalVenderList = array();

        if (is_string($findContext))
            $findVenderId = $findContext;

        if (is_array($findContext)) {
            $findVenderId = isset($findContext['venderId']) ? $findContext['venderId'] : NULL;
            $findVenderName = isset($findContext['venderName']) ? $findContext['venderName'] : NULL;
        }

        /*
          //first get all event
          $eventList = $this->findEventListByType($eventType);

          foreach ($eventList as $event) {
          $vender = $event->getMessageManager()->getMessage('vender');
          $venderId = $vender->getMediaManager()->getMedia('venderId')->getContent();
          //$venderName = $vender->getMediaManager()->getMedia('venderName');
          if ($findVenderId != NULL && $findVenderId == $venderId) {
          $finalVenderList[$vender->getId()] = $vender;
          } else {
          if ($findVenderName != NULL && (strpos($findVenderName, $venderName) || strpos($venderName, $findVenderName))) {
          $finalVenderList[$vender->getId()] = $vender;
          }
          }
          }

          $valueList = array();
          foreach ($finalVenderList as $vender) {
          $bookableList = $vender->getMessageManager()->getMessageList();
          foreach ($bookableList as $id => $bookable) {
          $bookableValueList = $this->findInputValueListByBookable($bookable);
          $valueList += $bookableValueList;
          }
          }

          return $valueList;
         * 
         */

        $findContext = array(
            'findCondition' => "name like 'bookable%'",
            'ownerData' => array('venderId' => $findVenderId),
        );

        $bookableList = BWMessage::findMessageList($findContext);

        $valueList = array();
        foreach ($bookableList as $id => $bookable) {
            $bookableValueList = $this->findInputValueListByBookable($bookable);
            $valueList += $bookableValueList;
        }

        return $valueList;

        //$sql = "SELECT ms._id,ms.name FROM tbl_message ms,tbl_media md, tbl_resource_media rmd where ms.name = 'vender' and md.name = 'venderId' and md.media_content = 'dfererer1' and rmd.media_id = md._id and rmd.resource_type = 'BWMessage' and rmd.resource_id = ms._id";
    }

    public function findInputValueListByCourtType($findContext, $eventType = 'booking.court') {

        //first find bookable for courtType
        if (is_string($findContext)) {
            $courtType = $findContext;
            $findContext = array(
                'findCondition' => "name like 'bookable%'",
                'mediaData' => array('courtType' => $courtType),
            );

            $bookableList = BWMessage::findMessageList($findContext);

            $valueList = array();
            foreach ($bookableList as $id => $bookable) {
                $bookableValueList = $this->findInputValueListByBookable($bookable);
                $valueList += $bookableValueList;
            }

            return $valueList;
        }
    }

    public function findVenderListByEventType($eventType = 'booking.court') {
        //first get all event
        $eventList = $this->findEventListByType($eventType);

        $venderList = array();

        foreach ($eventList as $event) {
            $vender = $event->getMessageManager()->getMessage('vender');
            $venderList[$vender->getId()] = $vender;
        }

        return $venderList;
    }

    public function findInputValueListByBookable($bookable, $condition = array(), $itemMatch = '=') {

        $bookable = $this->updateBookableInputValue($bookable);

        $inputValueTable = new BTreeTable('BWInputValue', $bookable);

        if (is_array($condition)) {
            if (!isset($condition['itemType']))
                $condition['itemType'] = 'TreeList';
            if (!isset($condition['itemData'])) {
                $condition['itemData'] = array();
            }
            $itemData = $condition['itemData'];
            //only get item for current space
            $condition['itemData']['spaceId'] = Blyn::app()->getActiveSpace()->getId();
            if (!isset($itemData['bookingStatus'])) {
                $condition['itemData']['bookingStatus'] = 'available';
            }
        }

        $valueList = $inputValueTable->getView($condition, $itemMatch);
        return $valueList;
    }

    public function findInputValueCountByBookable($bookable, $condition = array(), $itemMatch = '=') {

        $bookable = $this->updateBookableInputValue($bookable);

        $inputValueTable = new BTreeTable('BWInputValue', $bookable);

        if (is_array($condition)) {
            if (!isset($condition['itemType']))
                $condition['itemType'] = 'TreeList';
            if (!isset($condition['itemData'])) {
                $condition['itemData'] = array();
            }
            $itemData = $condition['itemData'];
            //only get count for current space
            $condition['itemData']['spaceId'] = Blyn::app()->getActiveSpace()->getId();
            if (!isset($itemData['bookingStatus'])) {
                $condition['itemData']['bookingStatus'] = 'available';
            }
        }

        $count = $inputValueTable->getCount($condition, $itemMatch);
        return $count;
    }

    /**
     * support two type find type, 'full' or 'fast'
     * @param type $findText
     * @param type $findType
     */
    public function findByFindText($findText, $findContext = array(), $isLimited = TRUE) {

        if ($findContext == NULL)
            $findContext = array();

        if (!isset($findContext['findType']))
            $findContext['findType'] = 'fast';

        if (!isset($findContext['itemMatch']))
            $findContext['itemMatch'] = 'like';

        $findType = $findContext['findType'];
        $itemMatch = $findContext['itemMatch'];

        //first parse findText
        $itemData = explode(' ', $findText);

        $itemContext = array();

        foreach ($itemData as $value) {
            $textList = explode('<', $value);
            $count = count($textList);
            if ($count == 2) {
                $itemContext[$textList[0] . '<'] = '<' . $textList[1];
                continue;
            }

            $textList = explode('>', $value);
            $count = count($textList);
            if ($count == 2) {
                $itemContext[$textList[0] . '>'] = '>' . $textList[1];
                continue;
            }

            $textList = explode('=', $value);
            $count = count($textList);
            if ($count == 2) {
                $itemContext[$textList[0]] = $textList[1];
            }
            if ($count == 1) {
                array_push($itemContext, $value);
            }
        }

        $city = Blyn::app()->getCurrentUser()->getAttribute('myCity_app' . Blyn::app()->getActiveApp()->getId())->getValue();

        $itemContext['city'] = $city;

        $findContext['itemData'] = $itemContext;

        //first update to latest data
        if ($findType == 'full') {

            $bookableFindContext = array(
                'mediaData' => array(
                    'city' => $city
                )
            );

            $bookableList = BWMessage::findMessageList($bookableFindContext);

            $valueList = array();
            foreach ($bookableList as $bookable) {
                //$this->updateBookableInputValue($bookable);
                $valueList += $this->findInputValueListByBookable($bookable, $findContext, $itemMatch);
            }
            return $valueList;
        }

        $condition = $findContext;

        $inputValueTable = new BTreeTable('BWInputValue');

        if (is_array($condition)) {
            if (!isset($condition['itemType']))
                $condition['itemType'] = 'TreeList';
            if (!isset($condition['itemData'])) {
                $condition['itemData'] = array();
                $condition['itemData']['city'] = $city;
            }
            $itemData = $condition['itemData'];
            //only get item for current space
            $condition['itemData']['spaceId'] = Blyn::app()->getActiveSpace()->getId();
            if (!isset($itemData['bookingStatus'])) {
                $condition['itemData']['bookingStatus'] = 'available';
            }
            if (!isset($itemData['city'])) {
                $condition['itemData']['city'] = $city;
            }
            if (isset($itemData['region']) && isset($itemData['city'])) {
                unset($condition['itemData']['city']);
            }
//            if (!isset($itemData['endTime'])) {
//                $condition['itemData']['endTime'] = '>' . time();
//            }
        }

        $limitStart = 0;
        if (isset($condition['limitStart']))
            $limitStart = $condition['limitStart'];

        $valueList = $inputValueTable->getView($condition, $isLimited);
        return $valueList;
    }

    public function findCountByFindText($findText, $findContext = array()) {

        if ($findContext == NULL)
            $findContext = array();

        if (!isset($findContext['findType']))
            $findContext['findType'] = 'fast';

        if (!isset($findContext['itemMatch']))
            $findContext['itemMatch'] = 'like';

        $findType = $findContext['findType'];
        $itemMatch = $findContext['itemMatch'];

        //first parse findText
        $itemData = explode(' ', $findText);

        $itemContext = array();

        foreach ($itemData as $value) {
            $textList = explode('<', $value);
            $count = count($textList);
            if ($count == 2) {
                $itemContext[$textList[0] . '<'] = '<' . $textList[1];
                continue;
            }

            $textList = explode('>', $value);
            $count = count($textList);
            if ($count == 2) {
                $itemContext[$textList[0] . '>'] = '>' . $textList[1];
                continue;
            }

            $textList = explode('=', $value);
            $count = count($textList);
            if ($count == 2) {
                $itemContext[$textList[0]] = $textList[1];
            }
            if ($count == 1) {
                array_push($itemContext, $value);
            }
        }
        if (!isset($itemContext['city'])) {
            $city = Blyn::app()->getCurrentUser()->getAttribute('myCity_app' . Blyn::app()->getActiveApp()->getId())->getValue();
            $itemContext['city'] = $city;
        }

        $findContext['itemData'] = $itemContext;

        //first update to latest data
        if ($findType == 'full') {

            $bookableFindContext = array(
                'mediaData' => array(
                    'city' => $itemContext['city']
                )
            );


            $bookableList = BWMessage::findMessageList($bookableFindContext);

            $count = 0;
            foreach ($bookableList as $bookable) {
                $this->updateBookableInputValue($bookable);
                $count += $this->findInputValueCountByBookable($bookable, $findContext, $itemMatch);
            }
            return $count;
        }

        $condition = $findContext;

        $inputValueTable = new BTreeTable('BWInputValue');

        if (is_array($condition)) {
            if (!isset($condition['itemType']))
                $condition['itemType'] = 'TreeList';
            if (!isset($condition['itemData'])) {
                $condition['itemData'] = array();
                $condition['itemData']['city'] = $city;
            }
            $itemData = $condition['itemData'];

            if (!isset($itemData['bookingStatus'])) {
                $condition['itemData']['bookingStatus'] = 'available';
            }
            if (!isset($itemData['city'])) {
                $condition['itemData']['city'] = $city;
            }
            if (isset($itemData['region']) && isset($itemData['city'])) {
                unset($condition['itemData']['city']);
            }
            if (!isset($itemData['endTime'])) {
                $condition['itemData']['endTime'] = '>' . time();
            }
        }
        //only get count for current space
        $condition['itemData']['spaceId'] = Blyn::app()->getActiveSpace()->getId();

        $count = $inputValueTable->getCount($condition);
        return $count;
    }

    public function findEventListByType($type) {
        $list = array();
        $eventList = array();
        $typeRoot = BWEventGroup::find('type');
        $eventType = $typeRoot->getChild($type);
        if ($eventType instanceof BWEventGroup) {
            $eventList = $eventType->getMembers(new BWEvent());
        }

        foreach ($eventList as $id => $event) {
            if ($event->spaceId == Blyn::app()->getActiveSpace()->getId()) {
                $list[$id] = $event;
            }
        }
        return $list;
    }

    /**
     * 
     * @param type $data
     */
    public function findMyBookingList($data = NULL) {

        $paidList = array();

        $cart = new BCart();

        $condition = array(
            'itemData' => array(
                'paymentStatus' => BCart::Payment_Status_Paid
            )
        );

        $view = $cart->getView($condition);
    }

    protected function updateBookableData($bookableId) {
        //get messages for court inputmedia and then populate inputable for inputMedia of court
        $bookableMessage = new BWMessage($bookableId);

        $inputMediaCourt = $bookableMessage->getInputMediaManager()->getInputMedia('court');
        $inputMediaTimeSlot = $bookableMessage->getInputMediaManager()->getInputMedia('timeSlot');

        $courtMessageList = $inputMediaCourt->getMessageManager()->getMessageList();

        //populate inputable for court inputmedia
        $this->populateCourtInputable($courtMessageList, $inputMediaCourt);

        //test populate inputable for timeslot inputMedia
        $inputType = $inputMediaTimeSlot->getInputType();
        if ($inputType instanceof BWTimeSlotType) {
            //populate inputable for timeSlot
            $timeSlotList = $inputType->getInputableList();
        }

        $courtInputType = $inputMediaCourt->getInputType();
        if ($courtInputType instanceof BWKeyValueType) {
            $courtList = $courtInputType->getInputableList();
        }

        $inputValueTable = $bookableMessage->getInputValueManager()->getInputValueTable('booking');

        if ($inputValueTable == NULL) {
            $inputValueTable = new BWInputValue();
            $bookableMessage->getInputValueManager()->addInputValueTable('booking');
        }

        foreach ($timeSlotList as $timeSlotId => $timeSlotInputable) {
            foreach ($courtList as $courtId => $courtInputable) {
                if ($inputValueTable instanceof BTreeTable) {
                    $inputValueTable->addList(array(
                        $courtId => $courtInputable->getValue(),
                        $timeSlotId => $timeSlotInputable->getValue(),
                        'status' => 'available'
                    ));
                }
            }
        }
    }

    public function updateBookableInputValue($bookable) {
        if (is_numeric($bookable)) {
            $bookableId = $bookable;
            $bookable = new BWMessage($bookableId);
        }

        $valueList = array();

        if ($bookable instanceof BWMessage) {

            $bookableId = $bookable->getId();

            $priceMedia = $bookable->getMediaManager()->getMedia('price');
            $price = NULL;
            if ($priceMedia instanceof BWMedia) {
                $price = $priceMedia->getContent();
            }

            $courtTypeMedia = $bookable->getMediaManager()->getMedia('courtType');
            $courtType = NULL;
            if ($courtTypeMedia instanceof BWMedia) {
                $courtType = $courtTypeMedia->getContent();
            }

            $regionMedia = $bookable->getMediaManager()->getMedia('region');
            $region = NULL;
            $regionAlias = NULL;
            $city = NULL;
            $cityAlias = NULL;
            if ($regionMedia instanceof BWMedia) {
                $region = $regionMedia->getContent();
                $regionNode = BWAddress::getRoot()->getChild($region);
                $regionAlias = $regionNode->getValue();
                $city = $regionNode->getParent()->getFullName();
                $cityAlias = $regionNode->getParent()->getValue();
            }

            $eventIdAttr = $bookable->getAttribute('eventId');
            $eventId = NULL;
            if ($eventIdAttr instanceof BAttribute) {
                $eventId = $eventIdAttr->value;
            }

            $eventNameAttr = $bookable->getAttribute('eventName');
            $eventName = NULL;
            if ($eventNameAttr instanceof BAttribute) {
                $eventName = $eventNameAttr->value;
            }

            $venderIdAttr = $bookable->getAttribute('venderId');
            $venderId = NULL;
            if ($venderIdAttr instanceof BAttribute) {
                $venderId = $venderIdAttr->value;
            }

            $venderNameAttr = $bookable->getAttribute('venderName');
            $venderName = NULL;
            if ($venderNameAttr instanceof BAttribute) {
                $venderName = $venderNameAttr->value;
            }

            $lastAddInputValueTime = NULL;

            $lastAddInputValueTimeAttribute = $bookable->getAttribute('lastAddInputValueTime');
            if ($lastAddInputValueTimeAttribute instanceof BAttribute) {
                $lastAddInputValueTime = $lastAddInputValueTimeAttribute->getValue();
            }
            $current = time();
            $inputValueTable = new BTreeTable('BWInputValue', $bookable);
            //$lastAddInputValueTime = NULL;
            //update inputvalue per hour
            if ($lastAddInputValueTime == NULL || $current > $lastAddInputValueTime + (60 * 60)) {
                $courtInputMedia = $bookable->getInputMediaManager()->getInputMedia('court');
                $timeSlotInputMedia = $bookable->getInputMediaManager()->getInputMedia('timeSlot');
                $courtList = $courtInputMedia->getInputType()->getInputableList();
                $timeSlotList = $timeSlotInputMedia->getInputType()->getInputableList();
                foreach ($courtList as $courtId => $courtName) {
                    foreach ($timeSlotList as $timeSlotId => $timeSlotInputable) {
                        $list = $inputValueTable->getList(array('itemData' => array('courtId' => $courtId, 'timeSlotId' => $timeSlotId)));
                        if (!$list instanceof BTreeList || $list->getId() == NULL) {
                            $inputValueList = array();
                            $inputValueList['courtName'] = $courtName;
                            $inputValueList['courtId'] = $courtId;
                            $inputValueList['timeSlotId'] = $timeSlotId;
                            $inputValueList['bookingStatus'] = 'available';
                            $inputValueList['bookableId'] = $bookableId;
                            $inputValueList['spaceId'] = Blyn::app()->getActiveSpace()->getId();

                            if ($price != NULL) {
                                $inputValueList['price'] = $price;
                            }

                            if ($courtType != NULL) {
                                $inputValueList['courtType'] = $courtType;
                            }

                            if ($region != NULL) {
                                $inputValueList['region'] = $region;
                            }

                            if ($regionAlias != NULL) {
                                $inputValueList['regionAlias'] = $regionAlias;
                            }

                            if ($city != NULL) {
                                $inputValueList['city'] = $city;
                            }

                            if ($cityAlias != NULL) {
                                $inputValueList['cityAlias'] = $cityAlias;
                            }

                            if ($eventId != NULL) {
                                $inputValueList['eventId'] = $eventId;
                            }

                            if ($eventName != NULL) {
                                //$inputValueList['eventName'] = $eventName;
                            }

                            if ($venderId != NULL) {
                                $inputValueList['venderId'] = $venderId;
                            }

                            if ($venderName != NULL) {
                                $inputValueList['venderName'] = $venderName;
                            }

                            $courtInputable = new BWInputAttribute($courtId);
                            $courtDisplayName = $courtInputable->getAttribute('displayName');
                            if ($courtDisplayName != NULL)
                                $inputValueList['courtDisplayName'] = $courtDisplayName->value;

                            $courtAddress = $courtInputable->getAttribute('address');
                            if ($courtAddress != NULL)
                                $inputValueList['courtAddress'] = $courtAddress->value;

                            $courtDescription = $courtInputable->getAttribute('description');
                            if ($courtDescription != NULL)
                                $inputValueList['courtDescription'] = $courtDescription->value;
                            //$courtInputable = new BWInputAttribute($courtId);

                            $timeSlot = new BWInputAttribute($timeSlotId);
                            $startTime = $timeSlot->getAttribute('startTime')->value;
                            $inputValueList['startTime'] = $startTime;
                            $startDate = date('Y-m-d', $startTime);
                            $inputValueList['startDate'] = $startDate;
                            $endTime = $timeSlot->getAttribute('endTime')->value;
                            $inputValueList['endTime'] = $endTime;
                            $inputValueList['startOfTimeSlot'] = date('His', $startTime);
                            $inputValueList['endOfTimeSlot'] = date('His', $endTime);
                            $inputValueList['startDay'] = date('N', $startTime);
                            $bookingStartTime = $timeSlot->getAttribute('bookingStartTime')->value;
                            $inputValueList['bookingStartTime'] = $bookingStartTime;
                            $bookingEndTime = $timeSlot->getAttribute('bookingEndTime')->value;
                            $inputValueList['bookingEndTime'] = $bookingEndTime;
                            $bookingCancelTime = $timeSlot->getAttribute('bookingCancelTime')->value;
                            $inputValueList['bookingCancelTime'] = $bookingCancelTime;

                            $inputValueTable->addList($inputValueList);
                        }
                    }
                }
                $bookable->addAttribute('lastAddInputValueTime', time());
            }

            return $bookable;
        }
    }

    public function getCityList($contry = 'china') {

        $chinaNode = BWAddress::getRoot()->getChild('china');

        if (!$chinaNode instanceof BWAddress) {
            $chinaNode = BWAddress::getRoot()->addChild(array('name' => 'china', 'value' => '中国'));
        }

        $chongqingNode = $chinaNode->getChild('tianjing');

        if (!$chongqingNode instanceof BWAddress) {
            $chinaNode->addChild(array('name' => 'chongqing', 'value' => '重庆'));
            $chinaNode->addChild(array('name' => 'beijing', 'value' => '北京'));
            $chinaNode->addChild(array('name' => 'shanghai', 'value' => '上海'));
            $chinaNode->addChild(array('name' => 'guangzhou', 'value' => '广州'));
            $chinaNode->addChild(array('name' => 'shenzhen', 'value' => '深圳'));
            $chinaNode->addChild(array('name' => 'chengdu', 'value' => '成都'));
            $chinaNode->addChild(array('name' => 'tianjing', 'value' => '天津'));
        }

        $cities = $chinaNode->getChildren();
        $cityList = array();

        foreach ($cities as $city) {
            $name = $city->getFullName();
            $citiName = $city->getValue();
            $cityList[$name] = $citiName;
        }

        return $cityList;
    }

    public function registerOperationMenu($operation, $data = NULL) {
//        $menuRoot = $operation->getMenu();
//        $menuRoot->addAttribute('bookingCourt', '场地预订');
//        $menuRoot->addAttribute('managebooking', '管理预订');
    }

    /**
     * 这个函数可以获得按日期排列的所有场地的数量，最多计算20天的数据
     * 注意startTime是INT数据，需要自己去变成日期显示
     * @param type $findText
     * @return type
     */
    public function findBookingItemCountByDate($findText = NULL) {

        if ($findText == NULL) {
            $findText = '';
        }

        $stringTime = date('Ymd');
        $initTime = strtotime($stringTime);

        $list = array();
        for ($i = 0; $i < 20; $i++) {
            $startTime = $initTime + $i * 24 * 60 * 60;
            $endTime = $startTime + 24 * 60 * 60;
            $findText = 'startTime>=' . $startTime . ' endTime<' . $endTime . ' ' . $findText;

            $count = $this->findCountByFindText($findText);
            $list[$startTime] = $count;
        }
        return $list;
    }

    public function findBookingItemsByTime($startTime, $endTime, $findText = NULL) {
        if ($findText == NULL)
            $findText = '';
        $findText = 'startTime>=' . $startTime . ' endTime<' . $endTime . ' ' . $findText;

        $view = $this->findByFindText($findText);
        return $view;
    }

    public function findBookingItemCountByTime($startTime, $endTime, $findText = NULL) {
        if ($findText == NULL)
            $findText = '';
        $findText = 'startTime>=' . $startTime . ' endTime<' . $endTime . ' ' . $findText;

        $view = $this->findCountByFindText($findText);
        return $view;
    }

}

?>
